package ua.com.fesvlast.hotel.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import ua.com.fesvlast.hotel.model.connectionpool.ConnectionManager;
import ua.com.fesvlast.hotel.model.enteties.Contacts;

public class ContactsDAO {
	private static Connection conn=ConnectionManager.getConnection();
	
	public  boolean createContact(Contacts contact){
		boolean flag=true;
		String sql="INSERT into contacts (firstName, lastname, email, phone, address, city, country, userId) VALUES (?,?,?,?,?,?,?,?)";
		PreparedStatement stmt=null;
		try{
			stmt=conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS );
			
			stmt.setString(1, contact.getFirstName());
			stmt.setString(2, contact.getLastName());
			stmt.setString(3, contact.getEmail());
			stmt.setString(4, contact.getPhone());
			stmt.setString(5, contact.getAddress());
			stmt.setString(6, contact.getCity());
			stmt.setString(7, contact.getCountry());
			stmt.setInt(8, contact.getUserId());
			stmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			flag=false;
		}
		ConnectionManager.releaseConnection(conn);
		return flag;
	}
	
	public Contacts getCurrentContactByID(int id){
		
		String sql="SELECT contactId, firstName, lastName, email, phone, address, city, country, userId"+
		" FROM contacts WHERE userId=?";
		PreparedStatement stmt=null;
		ResultSet rs=null;
		Contacts contact=null;
		
		try{
			stmt=conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			stmt.setInt(1, id);
			rs =stmt.executeQuery();
			
			while(rs.next()){
				contact=new Contacts();
				contact.setAddress(rs.getString("address"));
				contact.setCity(rs.getString("city"));
				contact.setContactId(rs.getInt("contactId"));
				contact.setCountry(rs.getString("country"));
				contact.setEmail(rs.getString("email"));
				contact.setFirstName(rs.getString("firstName"));
				contact.setLastName(rs.getString("lastName"));
				contact.setPhone(rs.getString("phone"));
				contact.setUserId(rs.getInt("userId"));
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		ConnectionManager.releaseConnection(conn);
		return contact;
	}
	
}
